<template>
  <div class="register-container">
       <van-cell-group>
  <van-field
    v-model="username"
    label="username"
    placeholder="username"
    @blur="checkusername"
    ref="username"
    required
  />

  <van-field
    v-model="nickname"
    label="nickname"
    placeholder="nickname"
    required
  />
   <van-field
    v-model="password"
    label="password"
    type="password"
    placeholder="password"
    required
  />
   <van-field
    v-model="mobile"
    label="mobile"
    placeholder="mobile"
    required
  />
</van-cell-group>
   <div class="vCode">
       <span class="text">验证码</span>
       <input type="text" v-model="vCode" placeholder="请输入验证码">
       <span ref="vcodeSvg" class="vcodeSvg" @click="refreshCode">获取验证码</span>
   </div>
<van-button type="info" size="normal" @click="getregister" class="btn-reg">注册</van-button>
  </div>
</template>
<script>
import Vue from 'vue'
import {Toast} from 'vant'
Vue.use(Toast)
export default {
    data(){
        return{
           username:"",
           nickname:"",
           password:"",
           vCode:"",
           mobile:""
        }
    },
    methods: {
        getvcode(){
           this.$http.get("v1/users/getVCode").then(result=>{
               if(result.status===200){
                   this.$refs.vcodeSvg.innerHTML=result.data
               }
           })
        },
        refreshCode(){
           this.getvcode()
        },
        checkusername(){
            this.$http.get("v1/users/checkUsername/" + this.username).then(res=>{
               if(res.data.status===200){
                 Toast("用户名可用")
               }else{
                 Toast("用户名不可用,请重新输入")
                 this.$refs.username.focus();
        
               }
            })
        },
        getregister(){
           let  userInfo={
            username:this.username,
            password:this.password,
            nickname:this.nickname,
            vCode:this.vCode,
            mobile:this.mobile
           }
           this.$http.post("v1/users/register",userInfo).then(result=>{
             console.dir(result)
               if(result.status==200){
                 this.$toast.success('注册成功')
                localStorage.setItem('token',result.data.data.token)
                 setTimeout(function(){
                   this.$router.push('/me/list')
                 },1000)
               }else{
                 this.$toast.fail('登录失败')
               }
           }).catch(err=>{
             console.dir(err)
           })
        }
       
    }
}
</script>
<style lang="less">
    .register-container{
        .vCode{
           height:50px;
           line-height: 50px;
           padding-left:30px;
           font-size:14px;
           text-align:left;
        input{
          border:none;
          width:45%;
          line-height: 50px;
          height:50px;
          margin-left:35px;
        }
      }
        .btn-reg{
          margin-top:10px;
        }
    }
</style>